<template>
  <div class="upload-icon-box flex-x" :class="goodsPicList.length ? 'have-file' : ''">
    <biz-cropper-upload
      action="string"
      list-type="picture-card"
      accept="image/png,image/jpg,image/jpeg"
      :on-preview="handlePictureCardPreview"
      :before-upload="onBeforeUploadImage"
      :http-request="UploadImagePic"
      :file-list="goodsPicList"
      :on-exceed="onExceedPic"
      :on-remove="onRemovePic"
      @cropperDone="picCropperDone"
      :limit="maxLimit"
      :tips="$t('goods.limit.imgLimit', { num1: maxLimit })"
      :cropper="{
        autoCropWidth: 80,
        autoCropHeight: 80,
        fixedNumber: [80, 80],
      }"
    ></biz-cropper-upload>
  </div>
</template>
<script>
import { defineComponent, ref, computed, watch } from 'vue'
import { previewElementImg } from '@src/common/entry'
import { Message } from 'element-ui'
import Uploader from 'packages/BaseUpload/uploader'

export default defineComponent({
  name: 'UploadIcon',
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    const goodsPicList = ref([])
    watch(
      () => props.value,
      value => {
        goodsPicList.value = value
      }
    )
    watch(
      () => goodsPicList.value,
      value => {
        emit('input', value)
      }
    )
    
    const maxLimit = ref(1)
    function handlePictureCardPreview(file) {
      previewElementImg(file.url)
      // this.$previewImg(file.url);
    }
    function onBeforeUploadImage(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt30M = file.size / 1024 / 1024 < 30

      if (!isJPG) {
        Message.error(this.$t('common.validate.imageType'))
      }
      if (!isLt30M) {
        Message.error(this.$t('common.validate.imageLimit', { limit: '30mb' }))
      }

      return isJPG && isLt30M
    }
    /**
		 * @description: 获取上传文件
		 * @param {Object} param el-upload 返回的文件格式
		 * @param {Boolean} isNeedUpload 是否需要调用上传接口
		 * @param {Object} files isNeedUpload 则需要带上files
		 * @return {Object} file
		 */
    async function handleGetFile(param, isNeedUpload = true, files) {
      let file = files
      if (isNeedUpload) {
        const result = await Uploader.upload(param.file, '/files/upload')
        if (result.status != 0) {
          Message({
            message: `${result.message}`,
            duration: 1500,
            type: 'error',
          })
          return null
        }
        file = result.data
      }
      return !file
        ? null
        : {
          uid: param.file.uid,
          fileId: file.id,
          filename: file.fileName,
          // 如果后端返回url,必须使用。如果后端不返回，需要拼接
          url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
          fileSize: file.fileSizeStr,
				  }
    }
    async function UploadImagePic(param) {
      const file = await handleGetFile(param)
      if (file) {
        goodsPicList.value = [...goodsPicList.value, file]
      }
    }
    async function picCropperDone(beforeFile, afterFile) {
      const result = await handleGetFile({ file: beforeFile }, false, afterFile)
      if (result) {
        goodsPicList.value = [...goodsPicList.value, result]
      }
    }
    // 文件超出个数限制时的钩子
    function onExceedPic() {
      Message.error(this.$t('common.validate.imgUploadLimit', { num: maxLimit.value }))
    }
    // 文件列表移除文件时的钩子
    function onRemovePic(o, a) {
      goodsPicList.value = goodsPicList.value.filter(item => item.uid != o.uid)
    }
    function setGoodsPicListBySystem(url) {
      goodsPicList.value = [
        {
          fileId: 'system_id',
          fileSize: '1KB',
          filename: 'system.png',
          status: 'success',
          uid: 20230826,
          url,
        },
      ]
    }
    return {
      handlePictureCardPreview,
      onBeforeUploadImage,
      UploadImagePic,
      goodsPicList,
      onExceedPic,
      onRemovePic,
      picCropperDone,
      setGoodsPicListBySystem,
      maxLimit,
    }
  },
})
</script>
<style lang="scss">
.have-file {
	.el-upload--picture-card {
		display: none;
	}
}
</style>
